<?php
require 'Slim/Slim.php';
require 'define.php';
require 'rb.php';
require 'function.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->hook('slim.before.router', function () use($app){
    if(checkDbConnection()){
        R::setup('mysql:host='.C('DB_HOST').';dbname='.C('DB_NAME').'',''.C('DB_USER').'',''.C('DB_PWD').'');
        R::freeze(true);
    }else{
        $app->halt('403','connction err please check db config');
    }
});

//首页路由
$app->get(
    '/',
    function () use($app){
            //管理首页
            $app->render('index.php');
    }
);
//查询所有的数据表
$app->get(
    '/tables',
    function () use ($app){
        $tables = R::getAll('show tables');
         // 按照JSON格式输出  
        foreach ($tables as  $value) {
            $dbname=C('DB_NAME');
            $data[]=$value["Tables_in_$dbname"];
        }
        $app->response()->header('Content-Type', 'application/json');
        echo json_encode( $data , JSON_NUMERIC_CHECK);
    }
);
//查询单张数据表的所有字段。

$app->get(
    '/tables/:name',
    function ($name) use ($app){
        $tableColumns = R::getColumns($name);
        //渲染操作页面
        $data = array('data' => $tableColumns);
        $app->render('rest.php',$data);
    }
);







































//查询所有led灯的状态
$app->get(
    '/leds',
    function () use ($app){

        $led_array = R::getAll('select * from leds');
         // 按照JSON格式输出  
        $app->response()->header('Content-Type', 'application/json');
        echo json_encode( $led_array , JSON_NUMERIC_CHECK);  
    }
);

//查询单个led灯的状态
$app->get(
    '/leds/:id',
    function ($id) use ($app){

        $led_single = R::getRow('select * from leds where id= :id',array(':id'=>$id));
         // 按照JSON格式输出  
        if($led_single){
            $app->response()->header('Content-Type', 'application/json');
            echo json_encode( $led_single , JSON_NUMERIC_CHECK);      
        }else{
            $app->response()->status(404);
        }

    }
);

//增加单个led灯

// POST route
$app->post(
    '/leds',
    function () use ($app) {
        $request = $app->request();  
        $body = $request->getBody();  
        $input = json_decode($body);
        $led=R::dispense( 'leds' );
        $led->description=$input->description;
        $led->status=$input->status;
        R::store($led);
    }
);

//更新单个led灯
$app->put(
    '/leds/:id',
    function ($id) use ($app){
        $request = $app->request();  
        $body = $request->getBody();  
        $input = json_decode($body);   
        // 查找编号为ID的记录  
        $led = R::findOne('leds', 'id=?', array($id));
        // 重新修改status状态，并保存  
        $led->status = (string)$input->status;
        R::store($led);      
    }
);

// PATCH route
$app->patch('/patch', function () {
    echo 'This is a PATCH route';
     
});

// 删除单个led
$app->delete(
    '/leds/:id',
    function ($id) use($app) {
        $led=R::dispense( 'leds' );
        $led->id=$id;
        R::trash( $led ); 
    }
);

$app->run();
